package ar.com.miguelgriffa.secureproperties.ant;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

import org.apache.tools.ant.BuildException;

import ar.com.miguelgriffa.secureproperties.SecureProperties;

/**
 * ANT Task to decrypt a propery file
 * 
 * @author mgriffa
 */
public class Decrypt extends BaseTask {

	@Override
	public void execute() throws BuildException {
		try {
			FileInputStream in = new FileInputStream(secure);

			if (plain.exists() && !overwrite) {
				throw new BuildException("Target file " + plain+ " already exists, delete it or set attribute overwrite='true'");
			}
			FileOutputStream out = new FileOutputStream(plain);

			SecureProperties p2 = new SecureProperties();
			if (key!=null) {
				p2.setKey(key);
			}
			p2.load(in);

			Properties p1 = new Properties();
			p1.putAll(p2);
			p1.store(out, header);
			out.close();

			if (verify) {
				verify(plain, secure);
			}

		} catch (Exception e) {
			throw new BuildException(e);
		}
	}
}
